package gagak.framework.web.support.request;

import gagak.framework.web.utils.Assert;

import java.util.LinkedHashMap;
import java.util.Map;

/*
 * @program: ce
 * @description: 抽象请求属性
 * @author: houhong
 * @create: 2022-11-23 17:10
 */
public abstract class AbstractRequestAttributes implements RequestAttributes {

    protected final Map<String, Runnable> requestDestructionCallbacks = new LinkedHashMap<String, Runnable>(16);

    private volatile boolean requestActive = true;

    public void requestCompleted() {
        executeDestructionCallBacks();
        updateAccessedSessionAttributes();
        this.requestActive = false;
    }

    protected final boolean isRequestActive() {
        return this.requestActive;
    }

    protected final void registerRequestDestructionCallback(String name, Runnable callback) {
        Assert.notNull(name, "Name must not be null");
        Assert.notNull(callback, "Callback must not be null");
        synchronized (this.requestDestructionCallbacks) {
            this.requestDestructionCallbacks.put(name, callback);
        }
    }


    protected final void removeRequestDestructionCallback(String name) {
        Assert.notNull(name, "Name must not be null");
        synchronized (this.requestDestructionCallbacks) {
            this.requestDestructionCallbacks.remove(name);
        }
    }

    /*
     * 执行回调
     */
    private void executeDestructionCallBacks() {

        synchronized (requestDestructionCallbacks) {
            for (Runnable runnable : requestDestructionCallbacks.values()) {
                runnable.run();
            }
            requestDestructionCallbacks.clear();
        }
    }

    protected abstract void updateAccessedSessionAttributes();

}